package com.ddtech.business.course.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddtech.business.course.entity.Course;
import com.ddtech.business.course.entity.CourseResource;
import com.ddtech.business.course.entity.CourseStudyRecord;
import com.ddtech.business.course.entity.CourseStudyRecordDetails;
import com.ddtech.business.course.mapper.CourseStudyRecordDetailsMapper;
import com.ddtech.business.course.mapper.CourseStudyRecordMapper;
import com.ddtech.business.course.query.CourseStudyRecordDetailsQuery;
import com.ddtech.business.course.service.CourseResourceService;
import com.ddtech.business.course.service.CourseService;
import com.ddtech.business.course.service.CourseStudyRecordDetailsService;
import com.ddtech.business.course.service.CourseStudyRecordService;
import com.ddtech.business.course.vo.res.CourseLearnHistoryVo;
import com.ddtech.business.course.vo.res.CourseStudyVo;
import com.ddtech.business.task.entity.Task;
import com.ddtech.business.task.entity.TaskUser;
import com.ddtech.business.task.mapper.TaskUserMapper;
import com.ddtech.business.task.service.TaskService;
import com.ddtech.business.task.service.TaskUserService;
import com.ddtech.business.train.entity.TrainPlan;
import com.ddtech.business.train.entity.TrainPlanResource;
import com.ddtech.business.train.entity.TrainPlanUser;
import com.ddtech.business.train.mapper.TrainPlanUserMapper;
import com.ddtech.business.train.service.TrainPlanResourceService;
import com.ddtech.business.train.service.TrainPlanService;
import com.ddtech.business.train.service.TrainPlanUserService;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import com.ddtech.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @version v1.0
 * @ClassName:CourseStudyRecordDetailsServiceImpl description：
 * @author:wei_zhang(xiao)
 * @date: 2023-06-08 13:40
 */
@Service
public class CourseStudyRecordDetailsServiceImpl  extends ServiceImpl<CourseStudyRecordDetailsMapper, CourseStudyRecordDetails>
        implements CourseStudyRecordDetailsService {

    @Resource
    private CourseStudyRecordDetailsMapper courseStudyRecordDetailsMapper;

    @Autowired
    private CourseResourceService courseResourceService;

    @Autowired
    private TrainPlanResourceService trainPlanResourceService;

    @Resource
    private TrainPlanUserMapper trainPlanUserMapper;

    @Autowired
    private TrainPlanUserService trainPlanUserService;

    @Resource
    private TaskUserMapper taskUserMapper;

    @Autowired
    private TaskUserService taskUserService;

    @Resource
    private CourseStudyRecordMapper courseStudyRecordMapper;

    @Autowired
    private CourseStudyRecordService courseStudyRecordService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private TrainPlanService trainPlanService;

    /***
     * description:查询当前课程个人当前学习到哪里
     * @param:  * @param courseStudyRecordDetailsQuery
     * @date: 2023-06-08
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object personInfo(CourseStudyRecordDetailsQuery courseStudyRecordDetailsQuery) {
        courseStudyRecordDetailsQuery.setUserId(SecurityUtils.getUserId());
        return courseStudyRecordDetailsMapper.personInfo(courseStudyRecordDetailsQuery);
    }


    /**
     * description:保存当前课程个人当前学习进度，视频定位
     * @param:  * @param courseStudyRecordDetails
     * @date: 2023-06-08
     * @return: void
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    @Transactional
    public void createXf(CourseStudyRecordDetails courseStudyRecordDetails) {
        CourseResource courseResource= courseResourceService.getById(courseStudyRecordDetails.getCourseResourceId());
        if (courseResource!=null) {
            courseStudyRecordDetails.setCourseResourceName(courseResource.getResourceName());
            courseStudyRecordDetails.setDuration(courseResource.getClassHour());
        }
        if(StringUtils.isEmpty(courseStudyRecordDetails.getCourseName())){
            Course course =courseService.getById(courseStudyRecordDetails.getCourseId());
            if(course!=null){
                courseStudyRecordDetails.setCourseName(course.getCourseName());
                String url=course.getThemeImage();
                if(StringUtils.isNotEmpty(url)){
                    JSONArray array = JSON.parseArray(url);
                    if (array!=null && array.size()>0){
                        JSONObject json=array.getJSONObject(0);
                        courseStudyRecordDetails.setThemeImage(json.getString("url"));
                    }
                }
            }
        }
        CourseStudyRecordDetailsQuery courseStudyRecordDetailsQuery=new CourseStudyRecordDetailsQuery();
        courseStudyRecordDetailsQuery.setUserId(SecurityUtils.getUserId());
        courseStudyRecordDetailsQuery.setCourseId(courseStudyRecordDetails.getCourseId());
        courseStudyRecordDetailsQuery.setCourseResourceId(courseStudyRecordDetails.getCourseResourceId());
        CourseStudyRecordDetails old=courseStudyRecordDetailsMapper.personInfo(courseStudyRecordDetailsQuery);
        if(old!=null){
            courseStudyRecordDetails.setId(old.getId());
        }
        courseStudyRecordDetails.init();
        if(StringUtils.isNotEmpty(courseStudyRecordDetails.getId())){
            courseStudyRecordDetails.setUpdateTime(LocalDateTime.now());
        }
        courseStudyRecordDetails.setType(0);
        courseStudyRecordDetails.setUserId(SecurityUtils.getUserId());
        courseStudyRecordDetails.setUserName(SecurityUtils.getName());
        this.saveOrUpdate(courseStudyRecordDetails);
    }


    /**
     * description:保存当前课程个人当前学习进度，视频定位
     * @param:  * @param courseStudyRecordDetails
     * @date: 2023-06-08
     * @return: void
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    @Transactional
    public void create(CourseStudyRecordDetails courseStudyRecordDetails) {
        CourseResource courseResource= courseResourceService.getById(courseStudyRecordDetails.getCourseResourceId());
        if (courseResource!=null) {
            courseStudyRecordDetails.setCourseResourceName(courseResource.getResourceName());
            courseStudyRecordDetails.setDuration(courseResource.getClassHour());
        }
        if(StringUtils.isEmpty(courseStudyRecordDetails.getCourseName())){
            Course course =courseService.getById(courseStudyRecordDetails.getCourseId());
            if(course!=null){
                courseStudyRecordDetails.setCourseName(course.getCourseName());
                String url=course.getThemeImage();
                if(StringUtils.isNotEmpty(url)){
                    JSONArray array = JSON.parseArray(url);
                    if (array!=null && array.size()>0){
                        JSONObject json=array.getJSONObject(0);
                        courseStudyRecordDetails.setThemeImage(json.getString("url"));
                    }
                }
            }
        }
        CourseStudyRecordDetailsQuery courseStudyRecordDetailsQuery=new CourseStudyRecordDetailsQuery();
        courseStudyRecordDetailsQuery.setUserId(SecurityUtils.getUserId());
        courseStudyRecordDetailsQuery.setCourseId(courseStudyRecordDetails.getCourseId());
        courseStudyRecordDetailsQuery.setCourseResourceId(courseStudyRecordDetails.getCourseResourceId());
        CourseStudyRecordDetails old=courseStudyRecordDetailsMapper.personInfo(courseStudyRecordDetailsQuery);
        if(old!=null){
            if(old.getIsFinish()==1){
                courseStudyRecordDetails.setIsFinish(1);
            }else{
                Integer classHours= courseResource.getClassHour();
                Integer nowTime=courseStudyRecordDetails.getResourceDuration();
                if(classHours!=null && nowTime!=null){
                    if(classHours-nowTime<2){//误差两秒以内，表示学习完成
                        courseStudyRecordDetails.setIsFinish(1);
                    }
                }
            }
            courseStudyRecordDetails.setId(old.getId());
        }else{
            Integer classHours= courseResource.getClassHour();
            Integer nowTime=courseStudyRecordDetails.getResourceDuration();
            if(classHours!=null && nowTime!=null){
                if(classHours-nowTime<2){//误差两秒以内，表示学习完成
                    courseStudyRecordDetails.setIsFinish(1);
                }else{
                    courseStudyRecordDetails.setIsFinish(0);
                }
            }
        }
        courseStudyRecordDetails.init();
        courseStudyRecordDetails.setType(0);
        courseStudyRecordDetails.setUserId(SecurityUtils.getUserId());
        courseStudyRecordDetails.setUserName(SecurityUtils.getName());

        //检验当前taskId和课程ID是否在同一个任务中，并属于当前登录人,防止界面缓存参数
        boolean contain=false;
        List<CourseStudyVo> ls =courseStudyRecordMapper.getBytaskIdAndUserId(courseStudyRecordDetails.getTaskId(),SecurityUtils.getUserId());
        for(CourseStudyVo courseStudyVo : ls){
            if(courseStudyVo.getCourseId().equals(courseStudyRecordDetails.getCourseId())){
                contain = true;
                break;
            }
        }
        if(!contain){
            courseStudyRecordDetails.setTaskId("");
        }
        this.saveOrUpdate(courseStudyRecordDetails);
        //如果当前课程管理任务，需要修改更新任务中课程学习进度
        if(contain){
            this.updateTaskProcess(courseStudyRecordDetails,courseStudyRecordDetailsQuery,ls);
        }
    }

    /***
     * description: 更新任务学习进度
     * @param:  * @param courseStudyRecordDetails
     * @param courseStudyRecordDetailsQuery
     * @date: 2023-06-28
     * @return: void
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    public  void updateTaskProcess(CourseStudyRecordDetails courseStudyRecordDetails,CourseStudyRecordDetailsQuery courseStudyRecordDetailsQuery,List<CourseStudyVo> ls){
        if(StringUtils.isNotEmpty(courseStudyRecordDetails.getTaskId())){
            CourseStudyRecord courseStudyRecord = courseStudyRecordMapper.getBytaskIdAndCourseIdAndUserId(courseStudyRecordDetails.getTaskId(),courseStudyRecordDetails.getCourseId(),SecurityUtils.getUserId());
            if(courseStudyRecord!=null){
                //计算任务课程学习进度
                Map<String,Object> data = courseStudyRecordDetailsMapper.personCourseStudyPercent(courseStudyRecordDetailsQuery);
                if(data!=null){
                    Object obj=data.get("nowStudyPercent");
                    if(obj!=null){
                        if(obj.toString().contains("100")){
                            courseStudyRecord.setIsFinish(1);
                        }else{
                            courseStudyRecord.setIsFinish(0);
                        }
                        courseStudyRecord.setFinishPercent(Double.parseDouble( obj.toString()));
                        courseStudyRecordService.saveOrUpdate(courseStudyRecord);
                    }
                }
            }else{
                CourseStudyRecord courseStudyRecordNew=new CourseStudyRecord();
                Task task = taskService.getById(courseStudyRecordDetails.getTaskId());
                if(task!=null){
                    courseStudyRecordNew.init();
                    courseStudyRecordNew.setIsFinish(0);
                    courseStudyRecordNew.setTaskId(courseStudyRecordDetails.getTaskId());
                    courseStudyRecordNew.setTaskName(task.getTaskName());
                    courseStudyRecordNew.setCourseId(courseStudyRecordDetails.getCourseId());
                    courseStudyRecordNew.setCourseName(courseStudyRecordDetails.getCourseName());
                    courseStudyRecordNew.setUserId(SecurityUtils.getUserId());
                    courseStudyRecordNew.setUserName(SecurityUtils.getName());
                    courseStudyRecordNew.setDuration(courseStudyRecordDetails.getResourceDuration());
                    courseStudyRecordService.saveOrUpdate(courseStudyRecordNew);
                }
            }
            TaskUser taskUser = taskUserMapper.getByUserdAndTaskId(courseStudyRecordDetails.getTaskId(),SecurityUtils.getUserId());
            if(taskUser!=null){
                //List<CourseStudyVo> ls =courseStudyRecordMapper.getBytaskIdAndUserId(courseStudyRecordDetails.getTaskId(),SecurityUtils.getUserId());
                boolean isFinish = true;
                for(CourseStudyVo courseStudyVo : ls){
                    if(courseStudyVo.getIsFinish()==0){
                        isFinish = false;
                        break;
                    }
                }
                if(isFinish){
                    taskUser.setIsFinish(1);
                    taskUser.setFinishTime(LocalDateTime.now());
                }else {
                    taskUser.setIsFinish(0);
                }
                taskUserService.saveOrUpdate(taskUser);
            }
        }
    }

    /***
     * description: 培训课程保存学习进度
     * @param:  * @param courseStudyRecordDetails
     * @date: 2023-06-26
     * @return: void
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    @Transactional
    public void trainCreate(CourseStudyRecordDetails courseStudyRecordDetails) {
        TrainPlanResource trainPlanResource= trainPlanResourceService.getById(courseStudyRecordDetails.getCourseResourceId());
        if (trainPlanResource!=null) {
            courseStudyRecordDetails.setCourseResourceName(trainPlanResource.getResourceName());
            courseStudyRecordDetails.setDuration(trainPlanResource.getClassHour());
        }
        if(StringUtils.isEmpty(courseStudyRecordDetails.getCourseName())){
            TrainPlan trainPlan=trainPlanService.getById(courseStudyRecordDetails.getCourseId());
            if(trainPlan!=null){
                courseStudyRecordDetails.setCourseName(trainPlan.getTrainName());
                String url=trainPlan.getThemeImage();
                if(StringUtils.isNotEmpty(url)){
                    JSONArray array = JSON.parseArray(url);
                    if (array!=null && array.size()>0){
                        JSONObject json=array.getJSONObject(0);
                        courseStudyRecordDetails.setThemeImage(json.getString("url"));
                    }
                }
            }
        }
        CourseStudyRecordDetailsQuery courseStudyRecordDetailsQuery=new CourseStudyRecordDetailsQuery();
        courseStudyRecordDetailsQuery.setUserId(SecurityUtils.getUserId());
        courseStudyRecordDetailsQuery.setCourseId(courseStudyRecordDetails.getCourseId());
        courseStudyRecordDetailsQuery.setCourseResourceId(courseStudyRecordDetails.getCourseResourceId());
        CourseStudyRecordDetails old=courseStudyRecordDetailsMapper.personInfo(courseStudyRecordDetailsQuery);
        if(old!=null){
            if(old.getIsFinish()==1){
                courseStudyRecordDetails.setIsFinish(1);
            }else{
                Integer classHours= trainPlanResource.getClassHour();
                Integer nowTime=courseStudyRecordDetails.getResourceDuration();
                if(classHours!=null && nowTime!=null){
                    if(classHours-nowTime<2){//误差两秒以内，表示学习完成
                        courseStudyRecordDetails.setIsFinish(1);
                    }
                }
            }
            courseStudyRecordDetails.setId(old.getId());
        }else{
            Integer classHours= trainPlanResource.getClassHour();
            Integer nowTime=courseStudyRecordDetails.getResourceDuration();
            if(classHours!=null && nowTime!=null){
                if(classHours-nowTime<2){//误差两秒以内，表示学习完成
                    courseStudyRecordDetails.setIsFinish(1);
                }else{
                    courseStudyRecordDetails.setIsFinish(0);
                }
            }
        }
        courseStudyRecordDetails.init();
        courseStudyRecordDetails.setType(1);
        courseStudyRecordDetails.setUserId(SecurityUtils.getUserId());
        courseStudyRecordDetails.setUserName(SecurityUtils.getName());
        this.saveOrUpdate(courseStudyRecordDetails);
        // 更新train_plan_user 表学习任务进度
        TrainPlanUser trainPlanUser=trainPlanUserMapper.getByUserdAndTrainId(SecurityUtils.getUserId(),courseStudyRecordDetails.getCourseId());
        if(trainPlanUser!=null){
            Map<String,Object> data = courseStudyRecordDetailsMapper.personTrainStudyPercent(courseStudyRecordDetailsQuery);
            if(data!=null){
                Object obj=data.get("nowStudyPercent");
                if(obj!=null){
                    if(obj.toString().contains("100")){
                        trainPlanUser.setIsFinish(1);
                        trainPlanUser.setFinishTime(LocalDateTime.now());
                    }else{
                        trainPlanUser.setIsFinish(0);
                    }
                    trainPlanUser.setFinishPercent(Double.parseDouble( obj.toString()));
                    trainPlanUserService.saveOrUpdate(trainPlanUser);
                }
            }
        }
    }

    @Override
    public Object personStudyHistory(CourseStudyRecordDetailsQuery courseStudyRecordDetailsQuery) {
        courseStudyRecordDetailsQuery.setUserId(SecurityUtils.getUserId());
        IPage<CourseLearnHistoryVo> page = courseStudyRecordDetailsMapper.personStudyHistory(courseStudyRecordDetailsQuery.populatePage(), courseStudyRecordDetailsQuery);
//        List<CourseLearnHistoryVo> list= page.getRecords().stream().map((courseLearnHistoryVo) -> {
//            String url=courseLearnHistoryVo.getThemeImage();
//            if(StringUtils.isNotEmpty(url)){
//                JSONArray array = JSON.parseArray(url);
//                if (array!=null && array.size()>0){
//                    JSONObject json=array.getJSONObject(0);
//                    courseLearnHistoryVo.setThemeImage(json.getString("url"));
//                }
//            }
//            return courseLearnHistoryVo;
//        }).collect(Collectors.toList());
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    /**
     * description: 查询个人课程学习进度
     * @param:  * @param courseStudyRecordDetailsQuery
     * @date: 2023-06-15
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Map<String,Object> personCourseStudyPercent(CourseStudyRecordDetailsQuery courseStudyRecordDetailsQuery) {
        courseStudyRecordDetailsQuery.setUserId(SecurityUtils.getUserId());
        Map<String,Object> data = courseStudyRecordDetailsMapper.personCourseStudyPercent(courseStudyRecordDetailsQuery);
        return data;
    }

    /**
     * description: 查询个人培训课程学习进度
     * @param:  * @param courseStudyRecordDetailsQuery
     * @date: 2023-06-15
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object personTrainStudyPercent(CourseStudyRecordDetailsQuery courseStudyRecordDetailsQuery) {
        courseStudyRecordDetailsQuery.setUserId(SecurityUtils.getUserId());
        return courseStudyRecordDetailsMapper.personTrainStudyPercent(courseStudyRecordDetailsQuery);
    }

    /***
     * description: app 课程首页课程学习统计数据
     * @param:  * @param
     * @date: 2023-07-04
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object courseStusyStatisticApp() {
        String userId=SecurityUtils.getUserId();
        return courseStudyRecordDetailsMapper.courseStusyStatisticApp(userId);
    }

    /***
     * description: 管理端首页统计数据-员工学习情况
     * @param:  * @param
     * @date: 2023-07-04
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object studyStatisticIndex() {
        List<Map<String,Object>> a= courseStudyRecordDetailsMapper.studyStatisticIndexTime();
        List<Map<String,Object>> b= courseStudyRecordDetailsMapper.studyStatisticIndexPerson();
        JSONObject json= new JSONObject();
        json.put("studyTime",a);
        json.put("studyPerson",b);
        return json;
    }
    /***
     * description: 管理端首页统计数据-员工学习TOP10
     * @param:  * @param
     * @date: 2023-07-04
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object studyStatisticTop10() {
        return courseStudyRecordDetailsMapper.studyStatisticTop10();
    }

    /***
     * description: 管理端首页统计数据-课程分类统计
     * @param:  * @param
     * @date: 2023-07-04
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object courseTypeStatistic() {
        return courseStudyRecordDetailsMapper.courseTypeStatistic();
    }

    /***
     * description: 管理端首页统计数据-今日学习人数、学习时间、人均学习时间
     * @param:  * @param
     * @date: 2023-07-04
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object todayStudyInfo() {
        SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        String yesterday=sf.format(cal.getTime());
        String toDay=sf.format(new Date());
        return courseStudyRecordDetailsMapper.todayStudyInfo(toDay,yesterday);
    }
}

